package com.ark.controller.system;

import com.ark.common.constant.Constants;
import com.ark.common.domain.entity.sys.SysRole;
import com.ark.common.domain.entity.sys.SysUser;
import com.ark.common.response.Result;
import com.ark.common.utils.EncryptionUtils;
import com.ark.common.utils.SecurityUtils;
import com.ark.security.service.PermissionService;
import com.ark.service.service.SysRoleService;
import com.ark.service.service.SysUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.ark.common.utils.SecurityUtils.getUserId;

@RestController
@RequestMapping("/api/user")
public class SysUserController {

    private final static Logger log = LoggerFactory.getLogger(SysUserController.class);

    @Resource
    private SysUserService userService;

    @Resource
    private SysRoleService roleService;

    @Resource
    private PermissionService permissionService;

    /**
     * 查询用户信息
     *
     * @param user 筛选条件
     */
    @RequestMapping("/list")
    public Result getUserList(SysUser user, @RequestParam(defaultValue = "1", value = "currentPage") int pageNum, @RequestParam(defaultValue = "10", value = "pageSize") int pageSize) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        IPage<SysUser> list = userService.selectUserList(page, user);
        return Result.success(list);
    }

    /**
     * 获取当前用户信息
     *
     * @return 用户信息
     */
    @RequestMapping("/info")
    public Result getUserInfo() {
        Result result = Result.success();
        //登录用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        //权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        result.put("user", user);
        result.put("roles", roles);
        result.put("permissions", permissions);
        return result;
    }

    /**
     * 更新用户信息
     *
     * @param user 用户信息
     */
    @PutMapping
    public Result updateUserInfo(@RequestBody SysUser user) {
        user.setDelFlag(null);
        user.setUsername(null);
        user.setStatus(null);
        user.setPassword(null);
        if (StringUtils.isNotEmpty(user.getEmail()) && userService.emailExist(user.getEmail())) {
            return Result.error("邮箱已存在");
        }
        return userService.updateUser(user) ? Result.success() : Result.error();
    }

    /**
     * 删除用户
     *
     * @param userIds 用户信息
     */
    @DeleteMapping("/{userIds}")
    public Result deleteUser(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) return Result.error("自杀失败!");
        return userService.deleteUserByIds(userIds) ? Result.success() : Result.error();
    }

    /**
     * 添加用户
     *
     * @param sysUser 用户信息
     */
    @PostMapping
    public Result addUser(@Valid @RequestBody SysUser sysUser) {
        if (userService.checkUserNameUnique(sysUser.getUsername())) return Result.error("账号已存在");
        if (StringUtils.isNotEmpty(sysUser.getEmail())&&userService.emailExist(sysUser.getEmail())) return Result.error("邮箱已存在");
        if (StringUtils.isNotEmpty(sysUser.getPassword())) sysUser.setPassword(SecurityUtils.encrypt(sysUser.getPassword()));
        return userService.insertUser(sysUser) ? Result.success() : Result.error();
    }

    /**
     * 获取当前用户信息
     *
     * @return 用户信息
     */
    @GetMapping(value = {"/","/{userId}"})
    public Result getUser(@PathVariable Long userId) {
        Result result = Result.success();
        List<SysRole> roles = roleService.selectAllRoles();
        result.put("roles",SysUser.isAdmin(userId)? roles :roles.stream().filter(r-> !r.isAdmin()).collect(Collectors.toList()));
        if (userId != null) {
            SysUser sysUser = userService.selectUserById(userId);
            result.put(Constants.DATA_TAG, sysUser);
        }
        return result;
    }
}
